﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using AllInOnePluginBL.Helpers;

namespace AllInOnePluginBL.FileHostingExtractors
{
    /// <summary>
    /// Summary description for ModovideoExtractor
    /// </summary>
    public class ModovideoExtractor : IFileHostingExtractor
    {
        private const string MOVIE_URL_FORMAT = "http://www.modovideo.com/frame.php?v={0}";
        private const string URL_REGEX = "'http://www.modovideo.com/frame.php\\?v=(.+?)'";

        public List<string> GetMovieUrls(string content)
        {
            var movieUrls = new List<string>();
            var exp = new Regex(URL_REGEX, RegexOptions.IgnoreCase);
            var matches = exp.Matches(content);
            foreach (Match match in matches)
            {
                if (match.Success)
                {
                    var movieUrl = string.Format(MOVIE_URL_FORMAT, match.Groups[1].Value);
                    if (!movieUrls.Contains(movieUrl))
                    {
                        movieUrls.Add(movieUrl);
                    }
                }
            }
            return movieUrls;
        }

        public VideoResult ExtractMovieUrl(string movieUrl)
        {
            var content = Utils.GetPage(movieUrl, Encoding.Default);

            var movieLinkMatch = Regex.Match(content, "plugin.video=(.+?)&", RegexOptions.IgnoreCase);
            if (!movieLinkMatch.Success)
            {
                throw new Exception("Cant find movie link");
            }

            return new VideoResult(movieLinkMatch.Groups[1].Value, true);
        }

        public bool IsContainVideoLink(string content)
        {
            var match = Regex.Match(content, "modovideo.com", RegexOptions.IgnoreCase);
            return match.Success;
        }
    }
}